package com.yuantu.judiciary.controller;

import cn.hutool.core.util.URLUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.payment.wap.models.AlipayTradeWapPayResponse;
import com.google.gson.Gson;
import com.yuantu.judiciary.common.Response;
import com.yuantu.judiciary.common.ResponseFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.*;

/**
 * 支付宝支付
 *
 * @author syw
 * @since 2023-09-05
 **/
@RestController
@RequestMapping(value = "/open/ali/pay")
@Api(tags = "支付宝支付接口")
@Slf4j
public class ApiAliPayController extends BaseController {

    Gson gson = new Gson();
    public static Config open_config;
//    public static String APP_ID = "2021004108624309";
//    public static String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCE9VO50fvp2QoviY7Uh7SsWUb0oP6qlpoB2Ui+h3VlGLJpZqitLXg0VFX3fmaGBxb/ThI58CYwfMOCg2CfOPvJBMLN5rRwJyUBRv1XJK9ZVZlALfJw2zP18N2eRxL6dLE+y/5iupdvUijUeH/Eu2moXLaqN1bOIqFHDqOd1sQlNfvxypr8OBrf7wK8uiZMrq6TAQganbcpA4P/CgFbOXVo19Zkr9Tvy8rFYcR95jMSmUOYYIo/+p5ee9NAzdZPp+XyOLgRTmdOsSU6QXu6I7Ac0WaGkN1oLQEBQfrn2SpLQ6qVWZnqZd80NKST0MfUSdzmgTQSPbUIXP4qeYpugow3AgMBAAECggEALY24T/Qn8WkR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oS3cEpoIwc7lVF2qCiU5i7rg3chZJ4UV6xkgv3BrvkXy1xs348o3i6S3tMgd0Ndnr1Y+w4TaXjkgMI20ynYKJIL6N3Ck3R5SWQ0dPRqiDeNKEMCQGQ9cyTQPmm1qXwv";
//    public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkiqi/5zpNJIaWGY52vOm8wlaHbl7XPZoDr4XbFsmwzbkuAQMtQOMcv62fmc0bfmFIuSXFXAXQloqcWF1q1+YfjFydDJW85iyvnpy8pqudlKHOrNV+3lFM+vmUuqUOXQECZO1ehZVDpY56EmuRTHE3q3PYCWw8m71kMYneAZ2o3u7dicPxuNnHp57j5TgooJH1L0EOQzc53AvrnwLVWikFyLY4Vb+k6sY5wdzDjQFMEeFQKZHV32JJlJA7grrd9Ja/ytTOfFGWU6VxTfkzHopKO1ym6vE8VYMD69Z3czv2mFn5WIirYYr9OxyKYp9oikSt+QOhaTRpRVve/mKGb4cBQIDAQAB";

    public static Config getOptions() {
        if (open_config == null) {
            Config config = new Config();
            config.protocol = "https";
            config.gatewayHost = "openapi.alipay.com";
  //          config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";
            config.signType = "RSA2";

//            config.appId = "2021004103655111";
//            config.appId = "2021004108624309";
//            config.appId = "9021000123618032";
         //   config.appId = "9021000127663508";
            config.appId = "2021004108624309";


            // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
//            config.merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCTHb+LMi7v7Et7tGWcV3UFRIk/BO2zE/sZsbrtBwzDgNECRI5AT/VZfzWfLFdFp3t43EWOZkUWZN7BK+zp4hw625FpWbintwBBSqiVkN0QiAG1noZqst+Uzkr4IK987VFz4QVsitJUXYKHQmV5qTyfOuxLsn1Fr80kDqJEGBCVEsLQ5eWxVmk/tk9yzoAEkRgXcD+qsPbi5FqkzDB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DRa9Vp6TvGbZi3ffPbDzvU4EhcLy38q3Co0hrKaM7PYWYpa4I9zdXATuRqtZOzUGnUOGGAHTcNB6avmR7aasDNBy1HkILgj/ehDhRbbvcF8Tvj/pFn8lvYgVeq70zeqb8KYgae5LfR536FzZ3WDe+zsawbI5wMJM1CYBWmj924PwKBgQC5oBZLz7oP/FUBIU22DHUaNPgb3oToIVOAfOUfw33qwpfInvHgiAdQplvoASJmAMb02emHqEcMe6+fr6lOddYm4Ldk2mC5lXBYqyepluHD/IQQLxQey2O/r0KkZoMYmhuh1j7ozTTOi31B2Z1mwf2DT+Q8tTkxFszlx9E9Yl32kwKBgDeybEIMy98MSu+SSgba2FjXhacuzRZEKmRb7NAka8xv5RHjC/KQCedplAplXHD2VA8jJ5tBKeEHReex26jPd5OP8xTzdDtxTrTA390pd/1WmU0b6WQx6wd77usBVfpqPuruA0DDJ7hlzxqbAv1pG3U5LcLSB7CbIRQkJd30qU1VAoGBAJn+TiDsnt4eJuL+HvsVUJzCLsboDniJFT313xs/0hlNACCmg+ES2Ia2zG4nasMWh/efRFaPawnXHnaqgxmdNmEgceSQKkgryn002H2ft4Ig3eqTM+zsLL9cBTxf8wgY6S2UkLIPc2yaWfqkLymNa+RhBea7LUwlLyy9XT/AeFVTAoGAbDxZzdNKRfhwiJNlhsB5sutgew8b8VSygXYPQgoG/yzHvSKe4UygcrgJggAl6xNRoNFgkVF1QDGSAG4kak7WFjDo4M878Qgsg392RZfllKy45nxBfL91yPGogMAnsy+3kBQZRP0stRbabIXlCua/yZm6PTTYjtFf78mvrSinnhQ=";

            //注：证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径，优先从文件系统中加载，加载失败后会继续尝试从CLASS_PATH中加载
//        config.merchantCertPath = "<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->";
//        config.alipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->";
//        config.alipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->";

            //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
//            config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";
//            config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";
           // config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkiqi/5zpNJIaWGY52vOm8wlaHbl7XPZoDr4XbFsmwzbkuAQMtQOMcv62fmc0bfmFIuSXFXAXQloqcWF1q1+YfjFydDJW85iyvnpy8pqudlKHOrNV+3lFM+vmUuqUOXQECZO1ehZVDpY56EmuRTHE3q3PYCWw8m71kMYneAZ2o3u7dicPxuNnHp57j5TgooJH1L0EOQzc53AvrnwLVWikFyLY4Vb+k6sY5wdzDjQFMEeFQKZHV32JJlJA7grrd9Ja/ytTOfFGWU6VxTfkzHopKO1ym6vE8VYMD69Z3czv2mFn5WIirYYr9OxyKYp9oikSt+QOhaTRpRVve/mKGb4cBQIDAQAB";
            config.alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";

            //可设置异步通知接收服务地址（可选）
//            config.notifyUrl = "https://cxb.learncoder.com:8901/api/open/ali/pay/notify";
        //    config.notifyUrl = "https://admin.njxnet.com:8901/api/open/ali/pay/notify";
            config.notifyUrl = "http://yuantu.natapp1.cc/api/order/notify/code/ali";

            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        //    config.encryptKey = "7qe0WUf9GVnfj/5qPGpmNA==";
            config.encryptKey = "7qe0WUf9GVnfj/5qPGpmNA==";

            return config;
        } else {
            return open_config;
        }
    }

    @ApiOperation(value = "创建订单")
    @GetMapping("/create/order")
    public Response<String> createOrder() {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            String tradeNo = UUID.randomUUID().toString().replace("-", "");
            log.info("创建订单号: {}", tradeNo);
            // 2. 发起API调用（以创建当面付收款二维码为例）
//            AlipayTradeAppPayResponse response = Factory.Payment.App().pay("测试商品", tradeNo, "0.01");
            AlipayTradeWapPayResponse response = Factory.Payment.Wap().pay("测试商品", tradeNo, "0.01", "http://47.100.124.208:8908/", "http://47.100.124.208:8908/result");
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                log.info("创建订单调用成功，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse(response.getBody());
            } else {
                log.info("创建订单调用失败，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse("");
            }
        } catch (Exception e) {
            log.error("创建订单调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "查看订单")
    @GetMapping("/query/order")
    public Response<String> queryOrder(@RequestParam String outTradeNo) {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            // 2. 发起API调用
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(outTradeNo);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                log.info("查看订单调用成功，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse(gson.toJson(response));
            } else {
                log.info("查看订单调用失败，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse("");
            }
        } catch (Exception e) {
            log.error("查看订单调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "关闭订单")
    @GetMapping("/close/order")
    public Response<String> closeOrder(@RequestParam String outTradeNo) {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            // 2. 发起API调用
            AlipayTradeCloseResponse response = Factory.Payment.Common().close(outTradeNo);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                log.info("关闭订单调用成功，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse(response.getOutTradeNo());
            } else {
                log.info("关闭订单调用失败，返回值：{}", gson.toJson(response));
                return ResponseFactory.okResponse("");
            }
        } catch (Exception e) {
            log.error("关闭订单调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @ApiOperation(value = "回调接口")
    @PostMapping(value = "/notify")
    public String aliNotify(HttpServletRequest request) throws Exception {
        BufferedReader br = request.getReader();
        String str = null;
        StringBuilder sb = new StringBuilder();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        log.info("支付回调构造参数: {}", sb);

        Map<String, String> params2 = getUrlQueryMap(URLUtil.decode(sb.toString(), "UTF-8"));
        log.info("支付回调请求参数2: {}", gson.toJson(getUrlQueryMap(URLUtil.decode(sb.toString(), "UTF-8"))));

        String outTradeNo = params2.get("out_trade_no");
        String tradeStatus = params2.get("trade_status");
        log.info("订单：{}，交易状态：{}", outTradeNo, tradeStatus);

        //回调的待验签字符串
        String resultInfo = URLUtil.decode(sb.toString(), "UTF-8");
        //编码格式
        String charset = "utf-8";
        //支付宝公钥
        String alipaypublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkiqi/5zpNJIaWGY52vOm8wlaHbl7XPZoDr4XbFsmwzbkuAQMtQOMcv62fmc0bfmFIuSXFXAXQloqcWF1q1+YfjFydDJW85iyvnpy8pqudlKHOrNV+3lFM+vmUuqUOXQECZO1ehZVDpY56EmuRTHE3q3PYCWw8m71kMYneAZ2o3u7dicPxuNnHp57j5TgooJH1L0EOQzc53AvrnwLVWikFyLY4Vb+k6sY5wdzDjQFMEeFQKZHV32JJlJA7grrd9Ja/ytTOfFGWU6VxTfkzHopKO1ym6vE8VYMD69Z3czv2mFn5WIirYYr9OxyKYp9oikSt+QOhaTRpRVve/mKGb4cBQIDAQAB";
        //签名方式
        String sign_type = "RSA2";
        //对待签名字符串数据通过&进行拆分
        String[] temp = resultInfo.split("&");
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        //把拆分数据放在map集合内
        for (int i = 0; i < temp.length; i++) {
            String[] arr = temp[i].split("=", 2); //通过"="号分割成2个数据
            String[] tempAagin = new String[arr.length]; //再开辟一个数组用来接收分割后的数据
            for (int j = 0; j < arr.length; j++) {
                tempAagin[j] = arr[j];
            }
            map.put(tempAagin[0], tempAagin[1]);
        }
        System.out.println(map);
        boolean verifyNotify = AlipaySignature.rsaCheckV1(map, alipaypublicKey, charset, sign_type);
        log.info("验签 ---> Factory.Payment.Common().verifyNotify 参数2结果: {}", verifyNotify);

//        Boolean verifyNotify1 = Factory.Payment.Common().verifyNotify(params1);
//        log.info("验签 ---> Factory.Payment.Common().verifyNotify 参数1结果: {}", verifyNotify1);
//        Boolean verifyNotify2 = Factory.Payment.Common().verifyNotify(params2);
//        log.info("验签 ---> Factory.Payment.Common().verifyNotify 参数2结果: {}", verifyNotify2);
//        Boolean verifyNotify3 = AlipaySignature.verifyV1(params1, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
//        log.info("验签 ---> AlipaySignature.verifyV1 参数1结果: {}", verifyNotify3);
//        Boolean verifyNotify4 = AlipaySignature.verifyV1(params2, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
//        log.info("验签 ---> AlipaySignature.verifyV1 参数2结果: {}", verifyNotify4);


        if (Boolean.TRUE.equals(verifyNotify)) {
//            String outTradeNo = request.getParameter("out_trade_no");
//            String tradeStatus = request.getParameter("trade_status");
            if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    log.info("订单：{}，交易成功，状态为：{}", outTradeNo, tradeStatus);
                } else {
                    log.info("订单：{}，交易失败，状态为：{}", outTradeNo, tradeStatus);
                }
            }
            return "success";
        } else {
            return "fail";
        }
    }

    public static Map<String, String> getUrlQueryMap(String str) {
        String urlQueryString = str;
        Map<String, String> queryMap = new HashMap<>();
        String[] arrSplit;
        if (urlQueryString == null) {
            return queryMap;
        } else {
            //每个键值为一组
            arrSplit = urlQueryString.split("[&]");
            for (String strSplit : arrSplit) {
                String[] arrSplitEqual = strSplit.split("[=]");
                //解析出键值
                if (arrSplitEqual.length > 1) {
                    queryMap.put(arrSplitEqual[0], arrSplitEqual[1]);
                } else {
                    if (!"".equals(arrSplitEqual[0])) {
                        queryMap.put(arrSplitEqual[0], "");
                    }
                }
            }
        }
        return queryMap;
    }

    public static Map<String, String> getQueryMap(HttpServletRequest request) {
        Enumeration enumeration = request.getParameterNames();
        Map<String, String> queryMap = new HashMap<>();
        while (enumeration.hasMoreElements()) {
            String paramName = (String) enumeration.nextElement();
            String[] values = request.getParameterValues(paramName);
            if (values.length != 0) {
                queryMap.put(paramName, values[0]);
            } else {
                queryMap.put(paramName, "");
            }
        }
        return queryMap;
    }

//    public static void main(String[] args) throws Exception {
//        // 1. 设置参数（全局只需设置一次）
//        Factory.setOptions(getOptions());
//        try {
//            // 2. 发起API调用（以创建当面付收款二维码为例）
////            AlipayTradeAppPayResponse response = Factory.Payment.App().pay("测试商品", "2234567899", "0.01");
////            AlipayTradeWapPayResponse response = Factory.Payment.Wap().pay("测试商品", "2234567895", "0.01", "https://enter.yuantusoft.com/home", "https://enter.yuantusoft.com/home");
////            AlipayTradeQueryResponse response = Factory.Payment.Common().query("f52fd17c42174d5686712feb41867201");
////                AlipayTradeQueryResponse response = Factory.Payment.Common().query("2234567899");
//            // 3. 处理响应或异常
//
//
//            String str = "gmt_create=2023-09-13+16%3A16%3A38&charset=UTF-8&seller_email=cddcce0202%40sandbox.com&subject=%E6%B5%8B%E8%AF%95%E5%95%86%E5%93%81&sign=a40hTx0e5t0UPUFCeEDLowtSm%2B2kXZg47gfjj%2BfgHcwirMux2%2BAA%2FKeGsT1FkUejNuKPoq%2Bz0cK4m0%2BltQRJdVQj04yl6FNIYus4rbsdvyZBVx%2BO%2BKtoCMl4UZoNlWNXyWW39RxJKVhD85AGMMATTyIkGnu06q7%2FPcbXtHC2zrvn%2Bqbv2uBSL0S7soGxgy7ua1wkz99kFspScFAW2lh5Dd8GkQv3%2BsgY1CAv8YJVqcHgEJxkb3XtN55EY2Vrk3U4PVZm7yW3yLCgjpVS15vhDFu1GOUvpt0tFpmwtCivF3YZ%2FzcE%2BWGLKo34ZVHEYoCQhKm8wRKXcszr2dy8n%2BgTMQ%3D%3D&buyer_id=2088722005630720&invoice_amount=0.01&notify_id=2023091301222161640130720500841914&fund_bill_list=%5B%7B%22amount%22%3A%220.01%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&trade_status=TRADE_SUCCESS&receipt_amount=0.01&app_id=9021000127663508&buyer_pay_amount=0.01&sign_type=RSA2&seller_id=2088721012757880&gmt_payment=2023-09-13+16%3A16%3A39&notify_time=2023-09-13+16%3A16%3A41&version=1.0&out_trade_no=1a29e389d0af4f9fbabfbb1380db8132&total_amount=0.01&trade_no=2023091322001430720500827887&auth_app_id=9021000127663508&buyer_logon_id=sochmt6523%40sandbox.com&point_amount=0.00";
//            Map<String, String> params2 = getUrlQueryMap(URLUtil.decode(str, "UTF-8"));
////            Boolean verifyNotify2 = Factory.Payment.Common().verifyNotify(params2);
//            //回调的待验签字符串
//            String resultInfo = URLUtil.decode(str, "UTF-8");
//            //编码格式
//            String charset = "utf-8";
//            //支付宝公钥
//            String alipaypublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkiqi/5zpNJIaWGY52vOm8wlaHbl7XPZoDr4XbFsmwzbkuAQMtQOMcv62fmc0bfmFIuSXFXAXQloqcWF1q1+YfjFydDJW85iyvnpy8pqudlKHOrNV+3lFM+vmUuqUOXQECZO1ehZVDpY56EmuRTHE3q3PYCWw8m71kMYneAZ2o3u7dicPxuNnHp57j5TgooJH1L0EOQzc53AvrnwLVWikFyLY4Vb+k6sY5wdzDjQFMEeFQKZHV32JJlJA7grrd9Ja/ytTOfFGWU6VxTfkzHopKO1ym6vE8VYMD69Z3czv2mFn5WIirYYr9OxyKYp9oikSt+QOhaTRpRVve/mKGb4cBQIDAQAB";
//            //签名方式
//            String sign_type = "RSA2";
//            //对待签名字符串数据通过&进行拆分
//            String[] temp = resultInfo.split("&");
//            LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
//            //把拆分数据放在map集合内
//            for (int i = 0; i < temp.length; i++) {
//                String[] arr = temp[i].split("=", 2); //通过"="号分割成2个数据
//                String[] tempAagin = new String[arr.length]; //再开辟一个数组用来接收分割后的数据
//                for (int j = 0; j < arr.length; j++) {
//                    tempAagin[j] = arr[j];
//                }
//                map.put(tempAagin[0], tempAagin[1]);
//            }
//            System.out.println(map);
//            boolean verifyNotify2 = AlipaySignature.rsaCheckV1(map, alipaypublicKey, charset, sign_type);
//            log.info("验签 ---> Factory.Payment.Common().verifyNotify 参数2结果: {}", verifyNotify2);
//
////            if (ResponseChecker.success(response)) {
////                log.info("调用成功，返回值：{}", JSON.toJSON(response));
////                System.out.println("调用成功");
////            } else {
////                log.info("调用失败，返回值：{}", JSON.toJSON(response));
////                System.err.println("调用失败，返回值：" + JSON.toJSON(response));
////            }
//        } catch (Exception e) {
//            System.err.println("调用遭遇异常，原因：" + e.getMessage());
//            throw new RuntimeException(e.getMessage(), e);
//        }
//    }

    public static void main(String[] args) {
        Gson GSON = new Gson();
        Factory.setOptions(getOptions());
        try {
            AlipayTradePagePayResponse response = Factory.Payment.Page().
                    pay("测试商品001", UUID.randomUUID().toString().replace("-", ""), "0.01", null);
            if (ResponseChecker.success(response)) {
                GSON.toJson(response.getBody());
            } else {
                log.info("二维码支付宝支付-创建订单失败，返回值：{}", GSON.toJson(response));
            }
        } catch (Exception e) {
            log.error("二维码支付宝支付-创建订单异常，原因：" + e.getMessage(), e);
        }
    }


}
